package Ut;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
//定义接口省略步骤,
public class DBUtil {
    public static DataSource dataSource;
    static {
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8"
                +"&allowPublicKeyRetrieval=true&useSSL=false" );
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("zyh22730267");
        dataSource=mysqlDataSource;
    }

    /**
     * 建立连接
     * @return
     */
    public  static Connection getConnect(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    private DBUtil(){}

    /**
     * 关闭数据库连接，并且二释放资源，释放资源建议由内至外面
     * @param connection
     * @param preparedStatement
     * @param resultSet
     * @param scanner
     */
    public static void close(Connection connection , PreparedStatement preparedStatement, ResultSet resultSet, Scanner scanner){

        scanner.close();
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
